package com.blog.serlvet;

import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.Blog;
import com.blog.bean.User;
import com.blog.dao.BlogDao;
import com.blog.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class BlogServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = LoginUtil.checkApiLogin(session, resp);
        if (user == null) {
            return;
        }

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        // 获取参数
        Integer blogId = null; // 允许为空
        try {
            blogId = Integer.valueOf(req.getParameter("id"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count = 0;
        try {
            count = Integer.parseInt(req.getParameter("count"));
        } catch (Exception e) {
            e.printStackTrace();
            count = 10;
        }
        int type = 1;
        try {
            type = Integer.parseInt(req.getParameter("type"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        BlogDao blogDao = new BlogDao();
        List<Blog> list = new ArrayList<>();
        try {
            if (type == 1) {
                // 最新微博
                list = blogDao.selectLatestBlog(blogId, count, user.getId());
            } else if (type == 2) {
                // 最热微博
                list = blogDao.selectHotBlog(blogId, count, user.getId());
            } else if (type == 3) {
                // 我的微博
                list = blogDao.selectMyBlog(blogId, count, user.getId());
            }
        } catch (Exception e) {
            resp.sendError(500);
            return;
        }
        writer.println(JSONObject.toJSONString(new BaseResponse(200, "获取微博成功", list)));
    }
}
